<template>
  <el-card shadow="hover">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">{{ title }}</span>
        <el-tag effect="plain" class="mr-1">
          {{ tip }}
        </el-tag>
      </div>
    </template>
    <el-row :gutter="20">
      <!-- <el-col :span="6" :offset="0" v-for="(item,index) in btns" :key="index">
                <el-card shadow="hover" class="border-0 bg-light-400">
                    <div class="flex flex-col items-center justify-center">
                        <span class="text-xl mb-2">{{ item.value }}</span>
                        <span class="text-xs text-gray-500">{{ item.label }}</span>
                    </div>
                </el-card>
            </el-col> -->
      <div ref="el" id="pie" style="width: 100%;height: 300px;"></div>
    </el-row>

  </el-card>

</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
// import { getAttackType } from '~/api/test.js'
import { useResizeObserver } from '@vueuse/core'
// import axios from "axios"
// import {getAttackType} from "~/api/test";
import {getAttackType} from "~/api/base";
defineProps({
  title: String,
  tip: String,
  // btns: Array
})

var myChart = null

onMounted(() => {
  var chartDom = document.getElementById('pie')
  if (chartDom) {
    myChart = echarts.init(chartDom)
    getData()
  }
})

onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart)
})

function getData() {
  const data = []
  getAttackType()
  // axios.get('/%2Fhome_page/Attack_type/')
  .then(res => {
    // 拿到{"":""}数据
    console.log("indexCard",res)
    const PieData = res
    // console.log(PieData)
    const keys = Object.keys(PieData).slice(0, 7) // 转换为数组，截取前7条数据
    const newObj = {} // 准备一个新对象

    keys.forEach(key => {
      newObj[key] = PieData[key] // 构建新对象
    })
    // console.log(newObj);
    // 外层嵌套数组
    for (const key in newObj) {
      data.push({ value: newObj[key], name: key })
    }
    myChart.setOption(option)
  })
  let option = {
    title: {
      text: '攻击类型占比',
      subtext: '比例',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      // data: Object.keys(PieData),
      left: 'left'
    },
    series: [
      {
        threatlevel: '攻击类型',
        type: 'pie',
        radius: '50%',
        data: data,
        // { value: data[0].value[1], name:data[0].value[0]  },
        // { value: 2, name: 'Email' },
        // { value: 0, name: 'Union Ads' },
        // { value: 6, name: 'Video Ads' },,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  myChart.setOption(option)
}

// vueuse 里面的 useResizeObserve   在使用myChart.resize() 重新自己设定大小
const el = ref(null)
useResizeObserver(el, entries => myChart.resize())
</script>
